package swu.edu.cn.javaee.component;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Base64.Encoder;
import java.util.Base64.Decoder;
import java.io.*;
import org.apache.commons.codec.binary.Base64;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.UUID;
@Component
public class Image {
    // 对字节数组字符串进行Base64解码并生成图片
    public static String GenerateImage(String imgStr)
    {  //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return null;
        final org.apache.commons.codec.binary.Base64 base64 =new org.apache.commons.codec.binary.Base64();

        /*BASE64Decoder decoder = new BASE64Decoder();*/
        try
        {
            /*byte[] b = decoder.decodeBuffer(imgStr);*/
            /*byte[] bytes=base64.encode(imgStr.getBytes());*/

            /*String encodeValues=base64.encodeToString(imgStr.getBytes());*/

            //Base64解码
            byte[] b=base64.decode(imgStr.getBytes());
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            String newfilename = System.currentTimeMillis() + UUID.randomUUID().toString().replace(".", "").substring(0, 6) + ".jpg" ;
            /*String fileLocation = "/static/images/";*/
            /*String filePath = "http://localhost:7071/"
                    + newfilename;*/
            String filePath= "/"+newfilename;
//        String head_portrait = filePath;//根路径+文件名
//        File file = new File("/www/javaweb/propaganda_system/picture/" + newfilename);
            //生成jpeg图片
//                String imgFilePath = "/www/javaweb/propaganda_system/picture/"+newfilename;//新生成的图片
            String imgFilePath = "D:\\NeijiangMSPPS\\JavaEE\\src\\main\\resources\\static\\images\\"+newfilename;//新生成的图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return filePath;
        }
        catch (Exception e)
        {
            return null;
        }
    }

}
